package com.xqboss.apps.service.aliyun;

import com.aliyun.cloudauth20190307.Client;
import com.aliyun.cloudauth20190307.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.xqboss.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *     阿里云人脸识别服务
 * </p>
 * @author Trent
 * @date 2023/9/12
 */
@Service
public class AliFaceService {


    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.faceAuth.sceneId}")
    private Long sceneId;

//    @Value("${aliyun.faceAuth.returnUrl}")
//    private String returnUrl;

    @Value("${aliyun.faceAuth.notifyUrl}")
    private String notifyUrl;


    /**
     * 请求实人认证
     *
     * @param outerOrderNo
     * @param idCardName
     * @param idCardNo
     * @param metaInfo
     * @return
     */
    public InitFaceVerifyResponseBody initFaceVerify(String outerOrderNo, String idCardName, String idCardNo, String metaInfo, String returnUrl, String callbackToken){
        InitFaceVerifyRequest request = new InitFaceVerifyRequest();
        // 请输入场景ID+L。
        request.setSceneId(sceneId);
        // 设置商户请求的唯一标识。
        request.setOuterOrderNo(outerOrderNo);
        // 认证方案。
        request.setProductCode("ID_PRO");
        // 模式。
        request.setModel("LIVENESS");
        request.setCertType("IDENTITY_CARD");
        request.setCertName(idCardName);
        request.setCertNo(idCardNo);
        // MetaInfo环境参数。
        request.setMetaInfo(metaInfo);
        request.setReturnUrl(returnUrl);
        //request.setMobile("130xxxxxxxx");
        //request.setIp("114.xxx.xxx.xxx");
        //request.setUserId("12345xxxx");
        request.setCallbackUrl(notifyUrl);
        request.setCallbackToken(callbackToken);
        // 如需开启个人信息加密传输。
        //request.setEncryptType("SM2");
        //request.setCertName("BCRD/7ZkNy7Q*****M1BMBezZe8GaYHrLwyJv558w==");
        //request.setCertNo("BMjsstxK3S4b1YH*****Pet8ECObfxmLN92SLsNg==");

        // 推荐，支持服务路由。
        InitFaceVerifyResponse response = initFaceVerifyAutoRoute(request);
        if(response == null){
            throw new ServiceException("认证申请失败！");
        }
        return response.getBody();
    }

    /**
     * 获取实人认证状态
     *
     * @return
     */
    public DescribeFaceVerifyResponse getFaceVerifyStatus(String certifyId){
        // 通过以下代码创建API请求并设置参数。
        DescribeFaceVerifyRequest request = new DescribeFaceVerifyRequest();
        // 请输入场景ID+L。
        request.setSceneId(sceneId);
        request.setCertifyId(certifyId);
        // 推荐，支持服务路由。
        DescribeFaceVerifyResponse response = describeFaceVerifyAutoRoute(request);
        return response;
    }

    private InitFaceVerifyResponse initFaceVerifyAutoRoute(InitFaceVerifyRequest request) {
        // 第一个为主区域Endpoint，第二个为备区域Endpoint。
        List<String> endpoints = Arrays.asList("cloudauth.cn-shanghai.aliyuncs.com", "cloudauth.cn-beijing.aliyuncs.com");
        InitFaceVerifyResponse lastResponse = null;
        for (int i=0; i<endpoints.size(); i++) {
            try {
                InitFaceVerifyResponse response = initFaceVerify(endpoints.get(i), request);
                lastResponse = response;

                // 服务端错误，切换到下个区域调用。
                if(response != null){
                    if(500 == response.getStatusCode()){
                        continue;
                    }
                    if(response.getBody() != null){
                        if("500".equals(response.getBody().getCode())){
                            continue;
                        }
                    }
                }
                // 正常返回
                return lastResponse;
            }catch (Exception e) {
                e.printStackTrace();
                if(i == endpoints.size()-1){
                    throw new RuntimeException(e);
                }
            }
        }

        return lastResponse;
    }

    private InitFaceVerifyResponse initFaceVerify(String endpoint, InitFaceVerifyRequest request)
            throws Exception {
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(accessKeySecret);
        config.setEndpoint(endpoint);
        Client client = new Client(config);

        // 创建RuntimeObject实例并设置运行参数。
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        return client.initFaceVerifyWithOptions(request, runtime);
    }

    private DescribeFaceVerifyResponse describeFaceVerifyAutoRoute(DescribeFaceVerifyRequest request) {
        // 第一个为主区域Endpoint，第二个为备区域Endpoint。
        List<String> endpoints = Arrays.asList("cloudauth.cn-shanghai.aliyuncs.com", "cloudauth.cn-beijing.aliyuncs.com");
        DescribeFaceVerifyResponse lastResponse = null;
        for (int i = 0; i < endpoints.size(); i++) {
            try {
                DescribeFaceVerifyResponse response = describeFaceVerify(endpoints.get(i), request);
                lastResponse = response;

                // 服务端错误，切换到下个区域调用。
                if (response != null) {
                    if (500 == response.getStatusCode()) {
                        continue;
                    }
                    if (response.getBody() != null) {
                        if ("500".equals(response.getBody().getCode())) {
                            continue;
                        }
                    }
                }

                return lastResponse;
            } catch (Exception e) {
                if (i == endpoints.size() - 1) {
                    throw new RuntimeException(e);
                }
            }
        }

        return lastResponse;
    }

    private DescribeFaceVerifyResponse describeFaceVerify(String endpoint, DescribeFaceVerifyRequest request)
            throws Exception {
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(accessKeySecret);
        config.setEndpoint(endpoint);
        Client client = new Client(config);

        // 创建RuntimeObject实例并设置运行参数。
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        return client.describeFaceVerifyWithOptions(request, runtime);
    }
}
